/**
 * 
 */
package com.google.code.server4j.parser;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.util.XMLErrorHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;

import com.google.code.server4j.core.CoreFactory;
import com.google.code.server4j.core.DefaultCoreFactory;
import com.google.code.server4j.thread.ThreadPool;

/**
 * @author Michael
 *
 */
public class ParseCoreFactory {

	private CoreFactory core = new DefaultCoreFactory();
	
	private Document doc;
	
    private Map<String,ThreadPool> threadPool = new HashMap<String, ThreadPool>();
	
	public void assemble() {
		Iterator<String> iter = threadPool.keySet().iterator();
		while(iter.hasNext()) {
			String id = iter.next();
			core.addTheadPool(threadPool.get(id));
		}
	}
	
	public void done()throws Exception {
		Iterator<String> iter = threadPool.keySet().iterator();
		while(iter.hasNext()) {
			String id = iter.next();
			ThreadPool pool = threadPool.get(id);
			pool.init();
			pool.start();
		}
	}
	
	
    /**
     * 校验 dtd 的（9php.com）方法
     * 
     * @param xmlFile
     *            xml文件路径
     * @param validationFile
     *            校验文件路径
     * @return 校验是否成功 
     */
    public boolean parse(final String xmlFile,final String validationFile) {
        /*
         * 此类实体包括在 DTD 内引用的（9php.com）外部 DTD
         * 子集和外部参数实体（无论哪种情形,仅在在解析器都读取外部参数实体时）
         * 和在文档元素内引用的（9php.com）外部通用实体（如果解析器读取外部通用实体）
         */
        EntityResolver resolver = new EntityResolver() {// 应用程序解析外部实体
            public InputSource resolveEntity(String publicId, String systemId) {
                InputStream is = null;
                try {
                    is = new FileInputStream(validationFile);// 读取dtd文档
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    return null;
                }
                InputSource ins = new InputSource(is);
                ins.setPublicId(publicId);
                ins.setSystemId(systemId);
                return ins;// 返回 InputSource实例
            }
        };
        SAXReader reader = new SAXReader(true);
        reader.setEntityResolver(resolver); // 向SAX 驱动器注册一EntityResolver个实例。
        boolean flag = validate(xmlFile, reader);// 调用验证方法
        parseXML(doc);
        return flag;
    }

    
    public void parseXML(Document doc) {
    	Element root = doc.getRootElement();  
        for (Iterator<?> ie = root.elementIterator(); ie.hasNext();) {
            
            Element element = (Element) ie.next();
            String elementName = element.getName();
            
            if("theadPool".equals(elementName)) {
            	ThreadPoolNode node = new ThreadPoolNode();
            	node.assembleThreadPool(element);
            	threadPool.putAll(node.getThreadPoolComponent());

            } else if("connector".equals(elementName)) {
            	
            } else if("container".equals(elementName)) {
            	
            } else if("attribute".equals(elementName)) {
            	
            } else if("lifecycle".equals(elementName)) {
            	
            } else if("component".equals(elementName)) {
            	
            } else  {
            	//error ! can not find the name~
            }
            
            
            

        }
    }
    

    /**
     * 
     * @param xmlFile xml文件路径
     * @param validationFile 校验文件路径 
     * @param reader  SAXReader 对象
     * @return 校验是否成功
     */
    private boolean validate(final String xmlFile, final SAXReader reader) {
        XMLErrorHandler errorHandle = new XMLErrorHandler();// 错误处理类实例
        reader.setErrorHandler(errorHandle);// 向 XML 阅读器注册一个实例
        File file = new File(xmlFile);
        InputStream is = null;
        if (file.exists() && file.isFile()) {
            try {
                is = new FileInputStream(file);// 读取xml
                InputStreamReader in = new InputStreamReader(is, "utf-8");
                doc = reader.read(in);
            } catch (FileNotFoundException e) {// 如果出现异常返回false
                e.printStackTrace();
                return false;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return false;
            } catch (DocumentException e) {
                e.printStackTrace();
                return false;
            }
        } else
            return false;
        if (errorHandle.getErrors().hasContent()) {// 如果错误处理类实例中包含错误信息返回false;
        	System.out.println("error : "+errorHandle.getErrorQName().toString());
        	System.out.println("warning : "+errorHandle.getWarningQName().toString());
            return false;
        }
        return true;
    }	
	
	
	public static void main(String[] args) {
		

	}

}
